<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game_model extends CI_Model {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
	function joined_game($game_id, $user_id, $killcode)
	{
	 	/*check to see if game is active/joinable/paused/non joinable/human win/zombie win
		find number of players AND humans and increase them by 1
	 	update the game_id for the user_id given with the game_id given
	 	update killcode in current_game with the killcode given
	 	set timed_tagged, starve_time, fed, and tags to 0
	 	set status id to human*/
		$records = $this->db->get_where("games",array('id'=> $game_id));
			foreach ($records->result() as $row) {
				$status_id = $row->Game_Status_id;
				$players = $row->players;
				$humans = $row->humans;
				$time_tagged = $row->time_tagged;
				$time_alive = $row->time_alive;
				$starve_time = $row->starve_time;
				$fed = $row->fed;
				$tags = $row->tags;
			}
			
			if($status_id == 1){
				$humans++;
				$players++;
				$data = array(
					'humans' => $humans,
					'players' => $players,
					'killcode' => $killcode,
					'time_tagged' => '0000-00-00 00:00:00',
					'time_alive' => '0000-00-00 00:00:00',
					'starve_time' => '0000-00-00 00:00:00',
					'fed' => 0,
					'tags' => 0
				);
				$this->db->where('User_id',$user_id);
				$this->db->update('current_game',$data);
				
				/*
					Update leaderboards.
				*/
				$e = new DateTime('0000-00-00 00:00:00');
				$f = clone $e;
				$e->add($time_alive);
				$e->add();
				$f = $f->diff($e)->format("Y-m-d G:i:s");
			}
			else
				return false;
	}
}	